#include <string>
#include <arpa/inet.h>
#include <stdio.h>
#include <sstream>
#include <iostream>
#include <iomanip>

/**
 * @brief 按16进制格式输出
 *
 */
void test_hex(struct sockaddr_in6 & in6) {
    unsigned char* p = (unsigned char*)&in6.sin6_addr;
    std::string result;
    std::ostringstream oss;
    for (int i = 0; i < 16; i += 2) { // ipv6由16个字节组成
        if (i > 0) {
            oss << ":";
        }
        //printf("%02x%02x", p[i], p[i+1]);
        oss << std::hex << std::setw(2) << std::setfill('0')
            << static_cast<int>(p[i]) << std::setw(2) << std::setfill('0')
            << static_cast<int>(p[i+1]);
    }
    printf("sockaddr拆分地址:%s", oss.str().c_str());
}


void test_binary(struct sockaddr_in6 & in6) {
    std::string result;
    unsigned char* p = (unsigned char*)&in6.sin6_addr;
    std::ostringstream oss;
    for (int i = 0; i < 16; i++) {
        if (i > 0) {
            oss << " " ;
        }
        for (int j = 7; j >= 0; --j) {
            oss << ((p[i] >> j) & 1);
        }
    }
    printf("二进制地址:%s\n", oss.str().c_str());
}

int main() {
    // 示例IPv6地址
    const char* ipstr = "2001:db8:1234:abcd:1:2:3:4";
    printf("原始地址:%s\n", ipstr);
    struct sockaddr_in6 in6;
    inet_pton(AF_INET6, ipstr, &(in6.sin6_addr));

    test_binary(in6);
    test_hex(in6);
    return 0;
}
